const express = require('express');
const app = express();
const port = 6868;

const cors = require('cors');
app.use(cors());

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'lzwl'
});

connection.connect((error) => {
  if (error) {
    console.error('无法连接到MySQL数据库', error);
  } else {
    console.log('已成功连接到MySQL数据库');
  }
});

app.use(express.json());

app.delete('/api/video/delete/:id', (req, res) => {
  const videoId = req.params.id;

  const sql = 'DELETE FROM t_video WHERE id = ?';
  const values = [videoId];

  connection.query(sql, values, (error, results, fields) => {
    if (error) {
      console.error('删除视频数据时发生错误', error);
      res.status(500).json({ error: '无法删除视频数据' });
    } else {
      console.log('视频数据已成功删除');
      res.status(200).json({ message: '视频数据已成功删除' });
    }
  });
});


app.post('/api/video/add', (req, res) => {
  const { name, addr } = req.body;

  const sql = 'INSERT INTO t_video (name, addr) VALUES (?, ?)';
  const values = [name, addr];

  connection.query(sql, values, (error, results, fields) => {
    if (error) {
      console.error('将视频数据插入数据库时发生错误', error);
      res.status(500).json({ error: '无法将视频数据插入数据库' });
    } else {
      console.log('视频数据已成功插入数据库');
      const newVideo = {
        id: results.insertId,
        name,
        addr
      };
      res.status(200).json(newVideo);
    }
  });
});

app.get('/api/video/list', (req, res) => {
  connection.query('SELECT * FROM t_video', (error, results, fields) => {
    if (error) {
      console.error('查询视频列表时发生错误', error);
      res.status(500).json({ error: '无法获取视频列表' });
    } else {
      res.status(200).json(results);
    }
  });
});

app.get('/api/video/:id', (req, res) => {
  const videoId = req.params.id;
  connection.query('SELECT * FROM t_video WHERE id = ?', [videoId], (error, results, fields) => {
    if (error) {
      console.error('查询视频时发生错误', error);
      res.status(500).json({ error: '无法获取视频信息' });
    } else {
      res.status(200).json(results);
    }
  });
});

app.listen(port, () => {
  console.log(`服务器已启动，监听端口 ${port}`);
});
